package com.task;

import com.task.model.SysJobPO;
import com.task.service.SysJobService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: cxt
 * @time: 2021/11/15
 * 系统启动之后执行定时任务
 */
@Component
public class SysJobRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);

    private SysJobService sysJobService;
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        logger.info("加载数据库里状态为正常的定时任务");
        List<SysJobPO> jobList = sysJobService.getSysJobAll(SysJobPO.STATE_NORMAL);

        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SysJobPO job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }
            logger.info("定时任务已加载完毕...任务数：{}个", jobList.size());
        }
    }

    @Autowired
    public void setSysJobService(SysJobService sysJobService) {
        this.sysJobService = sysJobService;
    }

    @Autowired
    public void setCronTaskRegistrar(CronTaskRegistrar cronTaskRegistrar) {
        this.cronTaskRegistrar = cronTaskRegistrar;
    }
}
